<?php
/**
 * Created by PhpStorm.
 * User: 曹旺
 * Date: 2018-04-20
 * Time: 09:56
 */
namespace app\index\model\pay;
use app\index\model\OrderCommodity;
use app\index\model\OrderRecord;
use think\Exception;
require_once(dirname(__FILE__).'/'."../../extend/wxpay/lib/WxPay.Api.php");
use think\Db;
use think\Model;
class H5pay extends Model{

    /**
     * @param $data微信返回的订单号（微信返回订单号的键transaction_id）
     * @param $key秘钥
     * @param $params自定义的参数
     * @return string
     * 处理回调
     * @author  曹旺
     * @data  15:54
     */
    public function notify($data,$params){
        try{
            //转换数据格式（xml string->array），校验数据
            $data = \WxPayResults::Init($data);
            $params['total_fee']=$data['total_fee'];
            Pay::fileLog($data, 'datas.log');
            $result=Db::table('nbsm_order')->where(['user_id'=>$params['user_id'],'order_number'=>$params['order_number'],'id'=>$params['order_id']])->find();
            if ($data && $result){
                $tradeNo = $data['transaction_id'];
                if($this->complete($tradeNo,$params)){
                    return 'success';
                }
            }
            //static::fileLog($data, 'datas.log');
            /*if($data && $this->verify($data)){
                //微信交易号
                $tradeNo = $data['transaction_id'];
                //处理订单
                if($this->complete($tradeNo)){
                    return 'success';
                }
            }*/
        }catch(\Exception $e){
            //if($this->debug){
            Pay::fileLog('notify:'.$e->getMessage(), 'debug.log');
            //static::fileLog($data, 'debugs.log');
            //}
        }
        return 'fail';
    }

    /**
     * @param $tradeNo
     * @param $data
     * @return bool
     * 支付成功后处理订单
     * @author  曹旺
     * @data  15:55
     */
    public function complete($tradeNo,$data){
        Db::startTrans();
        try{
            $order_state=Db::table('nbsm_order')->where(['id'=>$data['order_id'],'user_id'=>$data['user_id'],'order_number'=>$data['order_number']])->update(['order_state'=>2]);
            if ($order_state){
                $order_record=new OrderRecord();
                $res=$order_record->tradeNo($tradeNo,$data);
                if ($res){
                    $ress=new OrderCommodity();
                    $commodity_sale_num=$ress->commodity_sale_number($data['order_id']);
                    if (!$commodity_sale_num){
                        Pay::fileLog($commodity_sale_num, 'debugs.log');
                        throw new Exception('修改商品销售数量失败');
                    }
                }else{
                    Pay::fileLog($res, 'debugs.log');
                    throw new Exception('交易记录插入失败');
                }
            }else{
                throw new Exception('订单状态修改失败');
            }
            // 提交事务
            Db::commit();
            return true;
        }catch (Exception $e){
            $text = $e->getMessage();
            //文件日志
            Pay::fileLog($text, 'debug.log');
            // 回滚事务
            Db::rollback();
        }

    }

    /**
     * 文件日志
     * @author  曹旺
     * date 2018/3/22
     */
    public static function fileLog($data, $name){
        $file = fopen(Pay::getPath().'/'.$name, 'a');
        fwrite($file, date('Y-m-d H:i:s').PHP_EOL);
        if(is_array($data) || is_object($data)){
            foreach($data as $k => $v){
                fwrite($file, $k.':'.$v.';');
            }
        }else{
            fwrite($file, $data);
        }
        fwrite($file, PHP_EOL.PHP_EOL);
        fclose($file);
    }

    /**
     * 获取日志文件路径
     * @author  曹旺
     * date 2018/3/22
     */
    public static function getPath(){
        $path = RUNTIME_PATH . '/pay-log/' . date('Ym-d');
        if(!is_dir($path)){
            mkdir($path, 0777, true);
            chmod($path, 0777);
        }
        return $path;
    }
}